<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Profile</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <link rel="stylesheet" href="../Homepage/css/header.css">
    <link rel="shortcut icon" href="../header-footer/images/ico.jpg" type="image/x-icon">
    <link rel="stylesheet" href="../Homepage/css/header.css">
    <link rel="stylesheet" href="../header-footer/common.css">
    <!-- <link rel="stylesheet" href="new-student-setting.css"> -->
    <link rel="stylesheet" href="account-styles.css">
</head>
<style>
/*Uniformly reduce the spacing between input items, align labels and input boxes*/
.profile-form .form-label,
.profile-form .col-form-label {
margin-bottom: 0;
font-weight: 500;
}
.profile-form .form-control,
.profile-form textarea {
padding: 6px 10px;
font-size: 14px;
}
.profile-form .form-check-label {
font-weight: normal;
}
.profile-form .form-check-input {
margin-top: 0.1rem;
}
.profile-form .row {
margin-bottom: 12px;
}
/*Fine tune error message text size*/
.profile-form .text-danger {
font-size: 12px;
}
.avatar-wrapper {
width: 100px;
height: 100px;
position: relative;
cursor: pointer;
transition: box-shadow 0.3s ease;
}
.avatar-img {
width: 100%;
height: 100%;
object-fit: cover;
border-radius: 50%;
border: 2px solid #e5e5e5;
}
.avatar-overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.4);
opacity: 0;
transition: opacity 0.3s ease;
}
.avatar-wrapper:hover .avatar-overlay {
opacity: 1;
}


</style>
<body>
    <!-- 页眉 -->
    <header class="navbar">
        <div class="nav">
            <div class="logo">
                <a href="../Homepage/WebsiteHomepage.html"><img src="../header-footer/images/logo.jpg" alt="AceHub"></a>
            </div>
            <nav>
                <ul>
                    <!-- TODO 补充链接 -->
                    <li><a href="../Homepage/WebsiteHomepage.html">home page</a></li>
                    <li><a href="../Homepage/courseList.html">course</a></li>
                    <li><a href="../Homepage/league.html">Alliance colleges</a></li>
                    <li><a href="../Homepage/about-us.html">About Us</a></li>
                </ul>
            </nav>
        </div>
        
        <div class="info">
            <!-- TODO 补充链接 -->
        </div>
    </header>
 <!-- ═════ 主体内容 ═════ -->
<main class="container mt-5 main-content">
    <!-- ------ Tab 切换 ------ -->
    <ul class="nav nav-tabs" id="myTab" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="info-tab" data-bs-toggle="tab"
                    data-bs-target="#info-pane" type="button" role="tab"
                    aria-controls="info-pane" aria-selected="true">Basic information</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="password-tab" data-bs-toggle="tab"
                    data-bs-target="#password-pane" type="button" role="tab"
                    aria-controls="password-pane" aria-selected="false">Change Password</button>
        </li>
    </ul>

    <div class="tab-content" id="myTabContent">
        <!-- === 基本信息 === -->
        <div class="tab-pane fade show active" id="info-pane" role="tabpanel" aria-labelledby="info-tab" tabindex="0">
            <form id="profile-form" class="profile-form p-4">
                <!-- 头像 -->
                <div class="mb-3 row align-items-center">
                    <label class="col-sm-3 col-form-label text-end">head portrait:</label>
                    <div class="col-sm-9 d-flex align-items-center">
                        <div id="avatar-container" class="avatar-wrapper">
                            <img id="avatar-img" class="avatar-img" alt="头像">
                            <div id="avatar-overlay" class="avatar-overlay rounded-circle d-flex justify-content-center align-items-center">
                                <i class="bi bi-camera-fill text-white fs-4"></i>
                            </div>
                            <input type="file" id="change-avatar" class="d-none" accept="image/*">
                        </div>
                    </div>
                </div>

                <!-- 用户ID -->
                <div class="mb-3 row align-items-center">
                    <label for="userid" class="col-sm-3 col-form-label text-end">User ID:</label>
                    <div class="col-sm-9">
                        <span id="userid" class="form-control-plaintext"></span>
                    </div>
                </div>

                <!-- 昵称 -->
                <div class="mb-3 row align-items-center">
                    <label for="username" class="col-sm-3 col-form-label text-end">nickname</label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" id="username" required>
                    </div>
                </div>

                <!-- 性别 -->
                <div class="mb-3 row align-items-center">
                    <label class="col-sm-3 col-form-label text-end">Gender:</label>
                    <div class="col-sm-9 d-flex align-items-center">
                        <div class="form-check me-3">
                            <input class="form-check-input" type="radio" id="man"   name="gender" value="男">
                            <label class="form-check-label" for="man">male</label>
                        </div>
                        <div class="form-check me-3">
                            <input class="form-check-input" type="radio" id="woman" name="gender" value="女">
                            <label class="form-check-label" for="woman">female</label>
                        </div>
                        <div class="form-check">
                            <input class="form-check-input" type="radio" id="unknown" name="gender" value="不公开">
                            <label class="form-check-label" for="unknown">not public</label>
                        </div>
                    </div>
                </div>

                <!-- 手机 -->
                <div class="mb-3 row align-items-center">
                    <label for="phone" class="col-sm-3 col-form-label text-end">mobile phone:</label>
                    <div class="col-sm-9">
                        <input type="text" class="form-control" id="phone" required>
                        <span id="ph-error-message" class="text-danger small"></span>
                    </div>
                </div>

                

                <!-- 保存按钮 -->
                <div class="mb-3 row">
                    <div class="offset-sm-3 col-sm-9">
                        <button type="submit" class="btn btn-primary">save</button>
                        <div id="success-message" class="mt-3 alert alert-success d-none"></div>
                    </div>
                </div>
            </form>   <!-- ★ 补齐基本信息表单结束标签 -->
        </div>

        <!-- === 修改密码 === -->
        <div class="tab-pane fade" id="password-pane" role="tabpanel" aria-labelledby="password-tab" tabindex="0">
            <form id="reset-password-form" class="profile-form p-4">
                <div class="mb-3 row">
                    <label for="old-password" class="col-sm-3 col-form-label">Original password:</label>
                    <div class="col-sm-9">
                        <input type="password" class="form-control" id="old-password" placeholder="输入原密码" required>
                        <span id="op-error-message" class="text-danger small"></span>
                    </div>
                </div>

                <div class="mb-3 row">
                    <label for="password" class="col-sm-3 col-form-label">New password:</label>
                    <div class="col-sm-9">
                        <input type="password" class="form-control" id="password" placeholder="输入新密码" required>
                        <span id="pa-error-message" class="text-danger small"></span>
                    </div>
                </div>

                <div class="mb-3 row">
                    <label for="confirm-password" class="col-sm-3 col-form-label">Confirm new password:</label>
                    <div class="col-sm-9">
                        <input type="password" class="form-control" id="confirm-password" placeholder="再次输入新密码" required>
                        <span id="cp-error-message" class="text-danger small"></span>
                    </div>
                </div>

                <div class="mb-3 row">
                    <div class="offset-sm-3 col-sm-9">
                        <button type="submit" class="btn btn-primary">confirm</button>
                        <div id="success-message-password" class="mt-3 alert alert-success d-none"></div>
                    </div>
                </div>
            </form>
        </div>
    </div>
</main>

<!-- ═════ 页脚 ═════ -->
<footer class="footer mt-5">
    <div class="footer-content">
        <div class="footer-logo">
            <a href="#"><img src="../header-footer/images/logo.jpg" alt="AceHub"></a>
        </div>
        <div class="footer-text">
            <nav class="footer-nav">
                <ul>
                    <li><a href="#about">About Us</a></li>
                    <li><a href="#contact">Contact Us</a></li>
                    <li><a href="#privacy">Privacy Policy</a></li>
                    <li><a href="#terms">Term of service</a></li>
                </ul>
            </nav>
            <div class="footer-info">
                <p>&copy; 2025 AceHub reserves all rights</p>
            </div>
        </div>
    </div>
</footer>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
    <script src="../database.js"></script>
    <script src="../account/account.js"></script>
    <script>
        //Retrieve user information based on token
window.onload = function() {
const userid = localStorage.getItem('token');
//If a user logs in, display their profile picture in the info div; if not, display the login and registration button
if(userid) {
const user = JSON.parse(localStorage.getItem(userid));
document.querySelector('.info').innerHTML = `
                    <a href="../student/student-profile.html"><img id="user-head" src="${user.avatar}" alt="用户头像"></a>
                    <div class="card">
                        <ul>
                            <li><a href="../student/student-profile.html">My studies</a></li>
                            <li><a href="../account/student-setting.html">Account Settings </a></li>
                            <li><a id="logout" href="#logout">Log Out</a></li>
                        </ul>
                    </div>
                `;
                //如果点击退出登录，清除token
                document.getElementById('logout').addEventListener('click', () => {
                    localStorage.removeItem('token');
                    window.location.href = '../Homepage/WebsiteHomepage.html';
                });
            }
            else{
                document.querySelector('.info').innerHTML = `
                    <a href="../account/login.html"><button class="login">log on</button></a>
                    <a href="../account/register.html"><button class="register">register</button></a>
                `;
            }
        }
    </script>
    <!--主体内容初始化-->
    <script>
        //Select the first tab by default
// document.querySelector('.tabs-item').classList.add('active');
// document.querySelectorAll('.tabs-content')[0].style.display = 'block';
// document.querySelectorAll('.tabs-content')[1].style.display = 'none';
const userid = localStorage.getItem('token');
const user = JSON.parse(localStorage.getItem(userid));
const gender = user.gender;
const signature = user.signature;

document.getElementById('avatar-img').src = user.avatar;
document.getElementById('userid').textContent = user.userid;
document.getElementById('username').value = user.username;

// 正确使用 if/else
if (gender === 'non-public') {
    document.getElementById('unknown').checked = true;
} else if (gender === 'male') {
    document.getElementById('man').checked = true;
} else {
    document.getElementById('woman').checked = true;
}

document.getElementById('phone').value = user.phone;

if(signature) {document.getElementById('signature').value = signature;}
    </script>
    <script>
        //点击tab切换
        // document.addEventListener('DOMContentLoaded', () => {
        //     let tabs = document.querySelectorAll('.tabs-item');
        //     let tabContents = document.querySelectorAll('.tabs-content');
        //     tabs.forEach((tab, index) => {
        //         tab.addEventListener('click', (e) => {
        //             e.preventDefault();
        //             // 移除所有tabs的active类
        //             tabs.forEach(t => t.classList.remove('active'));
        //             tabContents.forEach(tc => tc.style.display = 'none');
        //             // 为当前点击的tab添加active类
        //             tab.classList.add('active');
        //             tabContents[index].style.display = 'block';
        //         });
        //     });
        // });
        //点击更换头像
        document.getElementById('avatar-container').addEventListener('click', () => {
            document.getElementById('change-avatar').click();
        });

        document.getElementById('change-avatar').addEventListener('change', (e) => {
            const file = e.target.files[0];
            if (!file) {
                return;
            }
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('avatar-img').src = e.target.result;
            }
            reader.readAsDataURL(file);
        });
        //离开手机号输入框时验证手机号
        document.getElementById('phone').addEventListener('blur', () => {
            const phone = document.getElementById('phone').value;
            checkPhone(phone);
        });
        //保存按钮点击事件
        document.getElementById('profile-form').addEventListener('submit', (e) => {
            e.preventDefault();
            const userid = localStorage.getItem('token');
            let user = JSON.parse(localStorage.getItem(userid));
            const phone = document.getElementById('phone').value;
            //验证手机号
            if(!checkPhone(phone)) return;
            //更新用户信息
            user.avatar = document.getElementById('avatar-img').src;
            user.username = document.getElementById('username').value;
            if(document.getElementById('man').checked) user.gender = '男';
            else if(document.getElementById('woman').checked) user.gender = '女';
            else if(document.getElementById('unknown').checked) user.gender = '不公开';
            user.phone = phone;
            user.signature = document.getElementById('signature').value;
            //更新localstorage
            localStorage.setItem(userid, JSON.stringify(user));
            //提示保存成功
            const successMsg = document.getElementById('success-message');
            successMsg.textContent = '保存成功！';
            successMsg.style.display = 'block';
            setTimeout(() => successMsg.classList.add('show'), 10);

            //1s后更新页面
            setTimeout(() => {
                location.reload();
            }, 1000);
        });

        //离开原密码输入框时验证原密码
        document.getElementById('old-password').addEventListener('blur', () => {
            checkOldPassword();
        });
        //离开新密码输入框时验证新密码
        document.getElementById('password').addEventListener('blur', () => {
            checkPassword();
        });
        //离开确认密码输入框时验证确认密码
        document.getElementById('confirm-password').addEventListener('blur', () => {
            checkConfirmPassword();
        });
        //确认按钮点击事件
        document.getElementById('reset-password-form').addEventListener('submit', (e) => {
            e.preventDefault();
            const userid = localStorage.getItem('token');
            let user = JSON.parse(localStorage.getItem(userid));
            const oldPassword = document.getElementById('old-password').value;
            let password = document.getElementById('password').value;
            const confirmPassword = document.getElementById('confirm-password').value;
            //验证信息是否填写完整
            if(!checkOldPassword() || !checkPassword() || !checkConfirmPassword()) return;
            //验证新密码和确认密码是否一致
            if(password !== confirmPassword) {
                document.getElementById('cp-error-message').textContent = '密码不一致，请重新输入';
                //清空密码输入框
                document.getElementById('old-password').value = '';
                document.getElementById('password').value = '';
                document.getElementById('confirm-password').value = '';
                return;
            }
            //验证原密码是否正确
            if(simpleHash(oldPassword, userid) !== user.password) {
                document.getElementById('op-error-message').textContent = '原密码错误';
                //清空密码输入框
                document.getElementById('old-password').value = '';
                document.getElementById('password').value = '';
                document.getElementById('confirm-password').value = '';
                return;
            }
            //更新密码
            password = simpleHash(password, userid);
            user.password = password;
            //更新localstorage
            localStorage.setItem(userid, JSON.stringify(user));
            //提示保存成功
            const successMsgPass = document.getElementById('success-message-password');
            successMsgPass.textContent = '密码修改成功！';
            successMsgPass.style.display = 'block';
            setTimeout(() => successMsgPass.classList.add('show'), 10);
            
            //2s后跳转到登录页面
            setTimeout(() => {
window.location.href = '../account/login.html';
}, 2000);
});
//Verify if password is filled in
function checkOldPassword() {
const oldPassword = document.getElementById('old-password').value;
if(!oldPassword) {
Document. getElementById ('op error message '). textContent=' Original password cannot be empty ';
return false;
}
else {
document.getElementById('op-error-message').textContent = '';
return true;
}
}
function checkPassword() {
const password = document.getElementById('password').value;
if(!password) {
Document. getElementById ('pa-error message '). textContent=' New password cannot be empty ';
return false;
}
else {
document.getElementById('pa-error-message').textContent = '';
return true;
}
}
function checkConfirmPassword() {
const password = document.getElementById('password').value;
const confirmPassword = document.getElementById('confirm-password').value;
if(!confirmPassword) {
Document. getElementById ('cp error message '). textContent=' Confirm password cannot be empty ';
return false;
}
else if(password !== confirmPassword) {
Document. getElementById ('cp error message '). textContent=' The passwords entered twice are inconsistent ';
return false;
}
else {
document.getElementById('cp-error-message').textContent = '';
return true;
}
}
    </script>
</body>
</html>
